import { useRef } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, Input, Popconfirm, Select, Table, Tag, Tooltip, TreeSelect } from 'antd';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { PlanStatusObj } from '@/enum/safety';
import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import {
  safePlanInfoDelete,
  safePlanInfoPage,
  safePlanInfoSubmit
} from '@/services/bizApi/anquanjihuaxinxijiekou';

import Dispose, { DisposeRef } from './dispose';
import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.SafePlanInfoEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const dispose = useRef<DisposeRef>(null);
  const [filter] = Filter.useForm();
  const treeDict = useRef<Record<number, DataNode>>({});
  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await safePlanInfoPage({
        ...formData,
        ...id,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                新增
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="address">
          <Select
            style={{ width: 180 }}
            placeholder="请选择地点"
            options={
              (store.dict['safetyPlanSite'] || []).map((item) => ({
                value: item.dicValue,
                label: item.dicName
              })) || []
            }
          />
        </Filter.Item>
        <Filter.Item name="name">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入名称"
          />
        </Filter.Item>
        <Filter.Item name="chargeDeptId">
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择负责部门"
            allowClear
          />
        </Filter.Item>
        {/* <Filter.Item name="type">
          <Select
            style={{ width: 180 }}
            placeholder="请选择类型"
            options={[
              {
                label: '月计划',
                value: '月计划'
              },
              {
                label: '周计划',
                value: '周计划'
              }
            ]}
          />
        </Filter.Item> */}
        <Filter.Item name="status">
          <Select
            style={{ width: 180 }}
            placeholder="请选择状态"
            options={[
              {
                label: '待提交',
                value: 1
              },
              {
                label: '待处理',
                value: 2
              },
              {
                label: '已完成',
                value: 3
              }
            ]}
          />
        </Filter.Item>
        {/* <Filter.Item name="chargeUserName">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入负责人"
          />
        </Filter.Item> */}

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 60,
            render: (_text, _record, index) => index + 1
          },
          {
            title: '地点',
            dataIndex: 'address'
          },
          {
            title: '名称',
            dataIndex: 'name',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip placement="top" title={text} arrow={true}>
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )
          },
          // {
          //   title: '类型',
          //   dataIndex: 'type'
          // },
          // {
          //   title: '负责部门',
          //   dataIndex: 'chargeDeptName'
          // },
          {
            title: '负责人',
            dataIndex: 'chargeUserName'
          },
          {
            title: '计划完成时间',
            dataIndex: 'finishTime',
            render: (v) => dayjs(v).format('YYYY-MM-DD')
          },
          {
            title: '状态',
            dataIndex: 'status',
            render: (v) => {
              const obj = PlanStatusObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '问题概况',
            dataIndex: 'problemOverview',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip placement="top" title={text} arrow={true}>
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && row?.status === 1 && (
                    <Popconfirm
                      title={`确定提交审核吗？`}
                      onConfirm={async () => {
                        const res = await safePlanInfoSubmit({
                          id: row.id as unknown as string
                        });
                        store.app?.message.success(res.message);
                        table.refresh();
                        return res.success;
                      }}
                    >
                      <Text type="primary">提交</Text>
                    </Popconfirm>
                  )}
                  {permission.check() &&
                    row?.chargeUserId === store?.user?.id &&
                    row?.status === 2 && (
                      <Text
                        onClick={() => {
                          dispose.current?.open({
                            rowData: row,
                            onSuccess: () => {
                              table.refresh();
                            }
                          });
                        }}
                        type="primary"
                      >
                        处理
                      </Text>
                    )}
                  {permission.check() && row?.status === 1 && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      编辑
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}

                  {permission.check() && row?.status === 1 && (
                    <Popconfirm
                      title={`确定删除吗？`}
                      onConfirm={async () => {
                        const res = await safePlanInfoDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success(res.message);
                        table.refresh();

                        return res.success;
                      }}
                    >
                      <Text type="danger">删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
      <Dispose ref={dispose} />
    </>
  );
};

export default Page;
